<template>
  <el-scrollbar>
    <div style="padding: 20px">
      <el-card class="box-card" shadow="never" style="margin-bottom: 10px">
        <div class="main_header">
          <div style="display: flex;justify-content: space-between">
            <div>
              <el-input
                v-model="searchData.username"
                style="width: 200px; margin-left: 10px"
                icon="el-icon-search"
                placeholder="请输入用户名搜索"
              />
              <el-button style="margin-left: 10px" type="primary" @click="load">搜索</el-button>
            </div>
            <div>
              <el-button type="primary" @click="addUser">
                <span style="vertical-align: middle"> 新增 </span></el-button>
            </div>
          </div>
        </div>
      </el-card>
      <el-card class="box-card" shadow="never">
        <el-table
          :data="tableData"
          stripe
          style="width: 100%"
          :header-cell-style="{
            color: 'black',
            background: 'rgb(250, 250, 250)',
            padding: '20px 0',
          }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" />
          <el-table-column prop="id" label="id" width="200" />
          <el-table-column prop="username" label="用户名" />
          <el-table-column prop="created_at" :formatter="dateFormat" label="创建时间" />
          <el-table-column prop="updated_at" :formatter="dateFormat" label="修改时间" />
          <el-table-column v-if="$store.state.user.is_super" label="是否停用" fixed="right">
            <template #default="scope">
              <el-switch
                v-model="scope.row.is_back_up"
                inline-prompt
                active-text="是"
                inactive-text="否"
                @change="new SwitchUserIsBack(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column v-else label="是否停用" fixed="right">
            <template #default="scope">
              <el-tag v-if="scope.row.is_back_up">是</el-tag>
              <el-tag v-else>否</el-tag>
            </template>
          </el-table-column>

          <el-table-column v-if="$store.state.user.is_super" label="管理员" fixed="right">
            <template #default="scope">
              <el-switch
                v-model="scope.row.is_super"
                inline-prompt
                active-text="是"
                inactive-text="否"
                @change="new SwitchUserIsSuper(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column v-else label="管理员" fixed="right">
            <template #default="scope">
              <el-tag v-if="scope.row.is_super">是</el-tag>
              <el-tag v-else>否</el-tag>
            </template>
          </el-table-column>

          <el-table-column v-if="$store.state.user.is_super" label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button
                style="margin-right: 10px"
                @click="form = {};dialogFormVisibleEditPwd = true;form.id = scope.row.id"
              >
                修改密码
              </el-button>
              <el-popover
                :ref="`popover-${scope.$index}`"
                placement="top"
                width="160"
              >
                <p>确定删除吗？</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="deltaskList(scope.$index)">取消</el-button>
                  <el-button type="primary" size="mini" @click="delUser(scope.row,scope.$index)">确定</el-button>
                </div>
                <el-button slot="reference" type="danger" icon="el-icon-delete" circle />
              </el-popover>

            </template>
          </el-table-column>
        </el-table>
        <div class="demo-pagination-block">
          <div style="margin: 20px 0">
            <el-pagination
              :current-page="pageNum"
              :page-size="pageSize"
              :page-sizes="[5, 10, 20]"
              layout="prev, pager, next"
              :total="total"
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </el-card>

    </div>
    <el-drawer
      title="添加用户"
      :visible.sync="centerDialogVisible"
    >
      <div style="padding: 20px 40px">
        <el-form ref="form" :label-position="label" label-width="80px" :model="form" :rules="rules">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" maxlength="20" placeholder="用户名" show-word-limit type="text" />
          </el-form-item>
          <div style="margin: 20px 0" />
          <el-form-item label="密码" prop="password">
            <el-input v-model="form.password" maxlength="32" placeholder="密码" show-word-limit type="text" />
          </el-form-item>
          <div style="margin: 40px 0" />
        </el-form>
        <div style="flex: auto;">
          <el-button @click="centerDialogVisible = false">返回</el-button>
          <el-button type="primary" @click="sendAddUser"> 确认</el-button>
        </div>
      </div>
    </el-drawer>
    <el-dialog title="修改密码" :visible.sync="dialogFormVisibleEditPwd" width="20%">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label="新密码" label-width="120px" prop="password">
          <el-input v-model="form.password" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleEditPwd = false">取 消</el-button>
        <el-button type="primary" @click="sendEditPwd">确 定</el-button>
      </div>
    </el-dialog>
  </el-scrollbar>
</template>
<script>
import { BackUpUser, CreateUser, DeleteUser, EditPassword, getPageList } from '@/api/user'
import moment from 'moment'
import store from '@/store'

export default {
  name: 'User',
  data() {
    return {
      label: 'top',
      loading: false,
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 5,
      searchData: {
        username: '',
        page_num: 1,
        page_size: 5
      },
      centerDialogVisible: false,
      dialogVisibleImg: false,
      dialogFormVisibleEditPwd: false,
      title: '用户信息',
      form: {},
      options: [
        {
          value: 1,
          label: '是'
        },
        {
          value: 0,
          label: '否'
        }
      ],
      rules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  computed: {
    is_super() {
      return this.$store.getters.is_super === 'true'
    }
  },
  created() {
    this.load()
  },
  methods: {
    deltaskList(index) {
      this.$refs[`popover-${index}`].doClose()
    },
    SwitchUserIsBack(row) {
      BackUpUser({ 'id': row.id, 'is_back_up': row.is_back_up }).then((res) => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: res.msg,
            type: 'success'
          })
          console.log(res.data)
        } else {
          this.$notify({
            title: '失败',
            message: res.msg,
            type: 'error'
          })
        }
        this.load()
      })
    },
    SwitchUserIsSuper(row) {
      BackUpUser({ 'id': row.id, 'is_super': row.is_super }).then((res) => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: res.msg,
            type: 'success'
          })
          console.log(res.data)
        } else {
          this.$notify({
            title: '失败',
            message: res.msg,
            type: 'error'
          })
        }
        this.load()
      })
    },
    dateFormat: function(row, column) {
      var date = row[column.property]
      if (date === undefined) {
        return ''
      }
      return moment(date).format('YYYY年MM月DD日 HH:mm:ss')
    },
    load() {
      this.loading = true
      this.searchData.page_num = this.pageNum
      this.searchData.page_size = this.pageSize
      getPageList(this.searchData).then(res => {
        this.tableData = res.data.data
        this.total = res.data.total
        this.loading = false
      })
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.load()
    },
    handleSelectionChange(val) {

    },
    addUser() {
      this.centerDialogVisible = true
      this.form = {}
    },
    delUser(row, index) {
      DeleteUser({ 'id': row.id }).then((res) => {
        this.$notify({
          title: '成功',
          message: res.msg,
          type: 'success'
        })
        this.$refs[`popover-${index}`].doClose()
        this.load()
      })
    },
    sendEditPwd() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          EditPassword(this.form).then(res => {
            this.$notify({
              title: '成功',
              message: res.msg,
              type: 'success'
            })
            this.load()
          })
          this.dialogFormVisibleEditPwd = false
        } else {
          this.dialogFormVisibleEditPwd = true
        }
      })
    },
    sendAddUser() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          CreateUser(this.form).then(res => {
            this.$notify({
              title: '成功',
              message: res.msg,
              type: 'success'
            })
            this.load()
          })
          this.centerDialogVisible = false
        } else {
          this.centerDialogVisible = true
        }
      })
    }
  }
}
</script>

<style scoped lang="sass">

</style>
